package com.dingding.gmall.product.web;

import com.dingding.gmall.product.entity.CategoryEntity;
import com.dingding.gmall.product.service.CategoryService;
import com.dingding.gmall.product.vo.Catelog2VO;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;

/**
 * @author liudingding
 * @ClassName IndexController
 * @description
 * @date 2021/3/7 7:14 下午
 */
@Controller
public class IndexController {

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedissonClient redissonClient;

    @GetMapping({"/","/index.html"})
    public String indexPage(Model model){
        List<CategoryEntity> categoryEntityList = categoryService.getLevel1Categorys();
        model.addAttribute("categorys", categoryEntityList);
        return "/index";
    }

    @GetMapping({"/item.html"})
    public String itemPage(Model model){
        return "/item";
    }

    @GetMapping("/index/catelog.json")
    @ResponseBody
    public Map<String, List<Catelog2VO>> getCatelogJson(){
        Map<String, List<Catelog2VO>> map = categoryService.getCatelogJsonFromCacheWithRedisLock();
        return map;
    }

    @ResponseBody
    @GetMapping("/test")
    public String test(){
        RLock myLock = redissonClient.getLock("myLock");
        myLock.lock();
        try {
            System.out.println("加锁成功，执行业务....."+Thread.currentThread().getId());
            Thread.sleep(10000);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            System.out.println("释放锁......"+Thread.currentThread().getId());
            myLock.unlock();
        }
        return "test";
    }
}
